﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ZK.CoalYardTransManage.Test
{
    public partial class 打印机打印测试 : Form
    {
        private int width_p = 210;//单位是mm

        private int height_p = 93;//单位是mm

        private int margin_lr = 2;//左右边距

        private int margin_tb = 2;//上下边距

        /// <summary>
        /// 需要打印的内容
        /// </summary>
        //public List<PrintInfo> PrintInfos { get; set; }

        //private PrintHelper printHelper = new PrintHelper();


        public 打印机打印测试()
        {
            InitializeComponent();
        }
        private static string GetFilePath()

        {

            string filepath = AppDomain.CurrentDomain.BaseDirectory;

            int binPos = filepath.IndexOf("bin");

            string binPath = filepath.Remove(binPos);

            return binPath;

        }
        private void button1_Click(object sender, EventArgs e)
        {
            //string strBinPath = GetFilePath();

            //Process pr = new Process();

            //pr.StartInfo.FileName =@"D:\lcw\project\HongXingMeiChang-2019-05-18\ZK.CoalYardTransManage\bin\Debug\1.txt";//文件全称-包括文件后缀

            //pr.StartInfo.CreateNoWindow = true;

            //pr.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            //pr.StartInfo.Verb = "Print";

            //pr.Start();

            PrintDialog printDialog = new PrintDialog();
            printDialog.ShowDialog();
            //printDialog
        }


        private Font printFont;
        private Font titleFont;
        private StringReader streamToPrint;
        private string  stringBuilder;
        private int leftMargin = 0;
        /// <summary>
        /// 转换毫米到百分之一英寸
        /// </summary>
        /// <param name="mm"></param>
        /// <returns></returns>
        private int MM2Inch(double mm)
        {
            return (int)(mm * 100.0f / 25.4f);
        }
        /// <summary>
        /// 设置PrintDocument 的相关属性
        /// </summary>
        /// <param name="str">要打印的字符串</param>
        public PrintDocument print()
        {
            try
            {
               
                // stringBuilder = new StringBuilder();
                //stringBuilder+=("<table>");
                //stringBuilder += ("<tr>");
                //stringBuilder += ("<td>");
                //stringBuilder += ("qwewqewqewqe我是一个中国人123213213213213<br/>aaaaaaa");
                //stringBuilder += ("</td>");
                //stringBuilder += ("</tr>");
                //stringBuilder += ("<table>");
                //stringBuilder += ("</table>");
                //streamToPrint = new StringReader(stringBuilder);
               // streamToPrint = new StringReader(str);


                printFont = new Font("宋体", 10);
                titleFont = new Font("宋体", 15);
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                pd.PrinterSettings.PrinterName = "DASCOM AR-300K";
                pd.DocumentName = pd.PrinterSettings.MaximumCopies.ToString();
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.pd_PrintPage);

                PrinterSettings printSetting = new PrinterSettings();
                printSetting.PrintRange = PrintRange.AllPages;


                int width_in = MM2Inch(width_p);
                int height_in = MM2Inch(height_p);
                PageSettings pageSetting = new PageSettings(printSetting);
                pageSetting.PaperSize = new PaperSize("customer", width_in, height_in);

                int margin_lr_in = MM2Inch(margin_lr);
                int margin_tb_in = MM2Inch(margin_tb);
                pageSetting.Margins = new Margins(margin_lr_in, margin_lr_in, margin_tb_in, margin_tb_in);
                pd.DefaultPageSettings = pageSetting;


                pd.PrintController = new System.Drawing.Printing.StandardPrintController();
                return pd;
               // pd.Print();
               //  pd.DefaultPageSettings.
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return null;
            }
        }


        private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {
            StringFormat 格式 = new StringFormat();
            格式.Alignment = StringAlignment.Center; //居中
            //格式.Alignment = StringAlignment.Far; //右对齐
            ev.Graphics.DrawString("铜川市耀州区照金矿业运销有限公司", new Font("宋体", MM2Inch(5)), Brushes.Black, new Rectangle(MM2Inch(0), MM2Inch(16), MM2Inch(210), MM2Inch(90)), 格式);//写字
            ev.Graphics.DrawString("日期："+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"                No: 12312321312312312", new Font("宋体", MM2Inch(3)), Brushes.Black, new Rectangle(MM2Inch(0), MM2Inch(26), MM2Inch(210), MM2Inch(90)), 格式);//写字


            //ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), 10, 10, 20, 20);//划线
            //ev.Graphics.DrawLines(new Pen(Brushes.Black, 1), new Point[] { });
            decimal zl = 12;
            double HBJ = 9;//行距
            double SXJL = 70;//列距
            StringFormat stringFormatBGZ = new StringFormat();//表格中字体格式
            stringFormatBGZ.Alignment = StringAlignment.Near; //水平
            stringFormatBGZ.LineAlignment = StringAlignment.Center;//垂直
            StringFormat stringFormatBGZ2 = new StringFormat();//表格中字体格式
            stringFormatBGZ2.Alignment = StringAlignment.Center; //水平
            stringFormatBGZ2.LineAlignment = StringAlignment.Center;//垂直
            for (int i = 1; i <= 5; i++)
            {
                string name1 = "";
                string name2 = "";

                switch (i)
                {
                   
                    case 1:
                        name1 = "收货单位";
                        name2 = "供货单位";
                        break;
                    case 2:
                        name1 = "";
                        name2 = "车    号";
                        break;
                    case 3:
                        name1 = "毛重                 皮重                  净重";
                        name2 = "";
                        break;
                    case 4:
                        name1 = "12323                 23221                232221";
                        name2 = "";
                        break;
                    case 5:
                        name1 = "司磅员     张红梅    司机签名";
                        name2 = "";
                        break;
                    
                    default:
                        break;
                }
                if (i == 3 || i ==4)
                {
                    ev.Graphics.DrawString(name1, new Font("宋体", MM2Inch(3.5)), Brushes.Black, new Rectangle(MM2Inch(25), MM2Inch((HBJ * i) + 22.8), MM2Inch(150), MM2Inch(9)), stringFormatBGZ2);//第一列字
                }
                else if (i ==5)
                {
                    ev.Graphics.DrawString(name1, new Font("宋体", MM2Inch(3.5)), Brushes.Black, new Rectangle(MM2Inch(68), MM2Inch((HBJ * i) + 22.8), MM2Inch(100), MM2Inch(9)), stringFormatBGZ2);//第一列字
                }
                else
                {
                    ev.Graphics.DrawString(name1, new Font("宋体", MM2Inch(3.5)), Brushes.Black, new Rectangle(MM2Inch(30.3), MM2Inch((HBJ * i) + 22.8), MM2Inch(75), MM2Inch(9)), stringFormatBGZ);//第一列字
                }
               
                ev.Graphics.DrawString(name2, new Font("宋体", MM2Inch(3.5)), Brushes.Black, new Rectangle(MM2Inch(100.3), MM2Inch((HBJ * i) + 22.8), MM2Inch(75), MM2Inch(9)), stringFormatBGZ);//第二列字
              
                    ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(30), MM2Inch((HBJ * i) + 30), MM2Inch(180), MM2Inch(30 + (HBJ * i)));//横线
                
               


            }
           
            for (int i = 0; i < 2; i++)
            {

                ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(50+ SXJL*i), MM2Inch(30), MM2Inch(50 + SXJL * i), MM2Inch(48));//中线两边

            }
            ev.Graphics.DrawRectangle(new Pen(Brushes.Black, 1), new Rectangle(MM2Inch(30), MM2Inch(30), MM2Inch(150), MM2Inch(45)));//矩形
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(100), MM2Inch( 30), MM2Inch(100), MM2Inch(48));//中线
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(100), MM2Inch( 30), MM2Inch(100), MM2Inch(48));//中线
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(80), MM2Inch( 48), MM2Inch(80), MM2Inch(75));//中线
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(130), MM2Inch( 48), MM2Inch(130), MM2Inch(75));//中线
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(105), MM2Inch( 66), MM2Inch(105), MM2Inch(75));//中线
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(155), MM2Inch( 66), MM2Inch(155), MM2Inch(75));//中线

        }

        #region MyRegion
        private void pd_PrintPage1(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {
            StringFormat 格式 = new StringFormat();
            格式.Alignment = StringAlignment.Center; //居中
            //格式.Alignment = StringAlignment.Far; //右对齐
            ev.Graphics.DrawString("铜川市耀州区照金矿业运销有限公司入煤单", new Font("宋体", MM2Inch(5)), Brushes.Black, new Rectangle(MM2Inch(0), MM2Inch(16), MM2Inch(210), MM2Inch(90)), 格式);//写字
            ev.Graphics.DrawString("日期：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "                No: 12312321312312312", new Font("宋体", MM2Inch(3)), Brushes.Black, new Rectangle(MM2Inch(0), MM2Inch(26), MM2Inch(210), MM2Inch(90)), 格式);//写字


            //ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), 10, 10, 20, 20);//划线
            //ev.Graphics.DrawLines(new Pen(Brushes.Black, 1), new Point[] { });
            decimal zl = 12;
            double HBJ = 7.5;//行距
            double SXJL = 70;//列距
            StringFormat stringFormatBGZ = new StringFormat();//表格中字体格式
            stringFormatBGZ.Alignment = StringAlignment.Near; //水平
            stringFormatBGZ.LineAlignment = StringAlignment.Center;//垂直
            for (int i = 1; i <= 6; i++)
            {
                string name1 = "";
                string name2 = "";
                switch (i)
                {

                    case 1:
                        name1 = "矿    发";
                        name2 = "车    号";
                        break;
                    case 2:
                        name1 = "扣    重";
                        name2 = "毛    重  " + zl;
                        break;
                    case 3:
                        name1 = "供货单位";
                        name2 = "皮    重";
                        break;
                    case 4:
                        name1 = "收货单位";
                        name2 = "实收净重";
                        break;
                    case 5:
                        name1 = "收货单位";
                        name2 = "收 煤 人";
                        break;
                    case 6:
                        name1 = "运    费";
                        name2 = "备    注";
                        break;
                    default:
                        break;
                }

                ev.Graphics.DrawString(name1, new Font("宋体", MM2Inch(3.5)), Brushes.Black, new Rectangle(MM2Inch(30.3), MM2Inch((HBJ * i) + 23.5), MM2Inch(75), MM2Inch(7.5)), stringFormatBGZ);//第一列字
                ev.Graphics.DrawString(name2, new Font("宋体", MM2Inch(3.5)), Brushes.Black, new Rectangle(MM2Inch(100.3), MM2Inch((HBJ * i) + 23.5), MM2Inch(75), MM2Inch(7.5)), stringFormatBGZ);//第二列字
                if (i < 6) ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(30), MM2Inch((HBJ * i) + 30), MM2Inch(180), MM2Inch(30 + (HBJ * i)));//横线
            }

            for (int i = 0; i < 2; i++)
            {

                ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(50 + SXJL * i), MM2Inch(30), MM2Inch(50 + SXJL * i), MM2Inch(75));//中线

            }
            ev.Graphics.DrawRectangle(new Pen(Brushes.Black, 1), new Rectangle(MM2Inch(30), MM2Inch(30), MM2Inch(150), MM2Inch(45)));//矩形
            ev.Graphics.DrawLine(new Pen(Brushes.Black, 1), MM2Inch(100), MM2Inch(30), MM2Inch(100), MM2Inch(75));//中线
            //float linesPerPage = 0;
            //float yPos = 0;
            //int count = 0;
            //float leftMargin = this.leftMargin;
            //float topMargin = 0;
            //String line = null;
            //linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
            //while (count < linesPerPage &&
            //((line = streamToPrint.ReadLine()) != null))
            //{
            //    if (count == 0)
            //    {
            //        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
            //        ev.Graphics.DrawString(line, titleFont, Brushes.Black, leftMargin + 10, yPos, new StringFormat());
            //    }
            //    else
            //    {
            //        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
            //        ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
            //    }
            //    count++;
            //}
            //if (line != null)
            //    ev.HasMorePages = true;
            //else
            //    ev.HasMorePages = false;

            //// 实例化一个word文档对象
            //PrintDocument doc = new PrintDocument();
            //// 加载文档
            //doc.LoadFromFile(@"C:\Users\Administrator\Desktop\示例文档.doc");
            //// 实例化System.Windows.Forms.PrintDialog对象
            //PrintDialog dialog = new PrintDialog();
            //dialog.AllowPrintToFile = true;
            //dialog.AllowCurrentPage = true;
            //dialog.AllowSomePages = true;
            //dialog.UseEXDialog = true;
            //// 关联doc.PrintDialog属性和PrintDialog对象
            //doc.PrintDialog = dialog;
            //// 后台打印
            //// PrintDocument printDoc = doc.PrintDocument; 
            //// printDoc.Print();
            //// 显示打印对话框并打印
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    //printDoc.Print();
            //}
        }
        #endregion


        //private void button2_Click(object sender, EventArgs e)
        //{
        //    print("1qwqww");
        //}

        private void 打印机打印测试_Load(object sender, EventArgs e)
        {
            //InitDocument();
        }

        private void button3_Click(object sender, EventArgs e)
        {

            print().Print();

        }

        private void 预览_Click(object sender, EventArgs e)
        {
            var printPriview = new PrintPreviewDialog
            {
                Document = print(),
                WindowState = FormWindowState.Maximized,
            };
            printPriview.ShowDialog();

          
        }

        //private void InitDocument()
        //{
        //    List<PrintInfo> lstPrintInfos = new List<PrintInfo>();
        //    PrintInfo p0 = new PrintInfo()
        //    {
        //        PrtType = PrintType.Table,
        //        PrtColor = Color.Brown,
        //        Row = int.Parse(this.txtRow.Text.Trim()),
        //        Column = int.Parse(this.txtColumn.Text.Trim()),
        //        Start = new Point(int.Parse(this.txtStart.Text.Trim(new char[] { '(', ')' }).Split(',')[0]), int.Parse(this.txtStart.Text.Trim(new char[] { '(', ')' }).Split(',')[1])),
        //        End = new Point(int.Parse(this.txtEnd.Text.Trim(new char[] { '(', ')' }).Split(',')[0]), int.Parse(this.txtEnd.Text.Trim(new char[] { '(', ')' }).Split(',')[1]))

        //    };
        //    lstPrintInfos.Add(p0);
        //    printHelper.PrintInfos = lstPrintInfos;
        //}

        //private void InitInfo()
        //{
        //    PrinterSettings printSetting = new PrinterSettings();
        //    printSetting.PrintRange = PrintRange.AllPages;


        //    int width_in = MM2Inch(width_p);
        //    int height_in = MM2Inch(height_p);
        //    PageSettings pageSetting = new PageSettings(printSetting);
        //    pageSetting.PaperSize = new PaperSize("customer", width_in, height_in);

        //    int margin_lr_in = MM2Inch(margin_lr);
        //    int margin_tb_in = MM2Inch(margin_tb);
        //    pageSetting.Margins = new Margins(margin_lr_in, margin_lr_in, margin_tb_in, margin_tb_in);
        //    this.pdControl.DefaultPageSettings = pageSetting;
        //}
        ///// <summary>
        ///// 转换毫米到百分之一英寸
        ///// </summary>
        ///// <param name="mm"></param>
        ///// <returns></returns>
        //private int MM2Inch(int mm)
        //{
        //    return (int)(mm * 100.0f / 25.4f);
        //}

        ///// <summary>
        ///// 打印事件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void pdControl_PrintPage(object sender, PrintPageEventArgs e)
        //{
        //    Font font = new Font("Arial", 14f, FontStyle.Regular);
        //    Graphics g = e.Graphics;
        //    g.PageScale = 1;
        //    g.PageUnit = GraphicsUnit.Millimeter;
        //    //先画一个矩形
        //    Pen lineColor = new Pen(Color.Black, 0.2f);
        //    g.FillRectangle(Brushes.Linen, 0, 0, width_p, height_p);
        //    printHelper.Print(g);
        //}
        ///// <summary>
        ///// 打印
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnPrint_Click(object sender, EventArgs e)
        //{
        //    //打印对话框
        //    if (this.ptDControl.ShowDialog() == DialogResult.OK)
        //    {
        //        this.pdControl.Print();
        //    }

        //}
        //private void lblColor_Click(object sender, EventArgs e)
        //{
        //    ColorDialog f = new ColorDialog();
        //    if (f.ShowDialog() == DialogResult.OK)
        //    {

        //        this.lblColor.BackColor = f.Color;
        //    }
        //}
        ///// <summary>
        ///// 刷新
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnRefresh_Click(object sender, EventArgs e)
        //{
        //    List<PrintInfo> lstPrintInfos = new List<PrintInfo>();
        //    //表格配置
        //    PrintInfo p0 = new PrintInfo()
        //    {
        //        PrtType = PrintType.Table,
        //        PrtColor = Color.Brown,
        //        Row = int.Parse(this.txtRow.Text.Trim()),
        //        Column = int.Parse(this.txtColumn.Text.Trim()),
        //        Start = new Point(int.Parse(this.txtStart.Text.Trim(new char[] { '(', ')' }).Split(',')[0]), int.Parse(this.txtStart.Text.Trim(new char[] { '(', ')' }).Split(',')[1])),
        //        End = new Point(int.Parse(this.txtEnd.Text.Trim(new char[] { '(', ')' }).Split(',')[0]), int.Parse(this.txtEnd.Text.Trim(new char[] { '(', ')' }).Split(',')[1]))

        //    };
        //    lstPrintInfos.Add(p0);
        //    //标题配置
        //    PrintInfo p1 = new PrintInfo()
        //    {
        //        PrtType = PrintType.Text,
        //        PrtColor = this.lblColor.BackColor,
        //        Content = this.txtTitle.Text.Trim(),
        //        Size = int.Parse(this.txtSize.Text.Trim()),
        //        FontStyle = chkBold.Checked ? FontStyle.Bold : FontStyle.Regular,
        //        Start = new Point(int.Parse(this.txtLocation.Text.Trim(new char[] { '(', ')' }).Split(',')[0]), int.Parse(this.txtLocation.Text.Trim(new char[] { '(', ')' }).Split(',')[1]))
        //    };
        //    lstPrintInfos.Add(p1);
        //    //内容
        //    TextBox[] T = new TextBox[12] { T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12 };
        //    TextBox[] L = new TextBox[12] { L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12 };
        //    for (int i = 0; i < 12; i++)
        //    {
        //        PrintInfo p = new PrintInfo()
        //        {
        //            PrtType = PrintType.Text,
        //            PrtColor = Color.Black,
        //            Content = T[i].Text.Trim(),
        //            Size = 12,
        //            FontStyle = FontStyle.Regular,
        //            Start = new Point(int.Parse(L[i].Text.Trim(new char[] { '(', ')' }).Split(',')[0]), int.Parse(L[i].Text.Trim(new char[] { '(', ')' }).Split(',')[1]))
        //        };
        //        lstPrintInfos.Add(p);
        //    }
        //    //打印时间
        //    PrintInfo p2 = new PrintInfo()
        //    {
        //        PrtType = PrintType.Text,
        //        PrtColor = this.lblColor.BackColor,
        //        Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
        //        Size = 11,
        //        FontStyle = FontStyle.Regular,
        //        Start = new Point(145, 63)
        //    };
        //    lstPrintInfos.Add(p2);

        //    printHelper.PrintInfos = lstPrintInfos;
        //    this.ppVControl.InvalidatePreview();//刷新文档的预览，重新调用PrintDocument的Print方法
        //}
    }
}
